package com.ikan.positionserver.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ikan.positionserver.entity.CloudHost;
import com.ikan.positionserver.entity.Device;
import com.ikan.positionserver.entity.PhysicalHost;
import com.ikan.positionserver.entity.TenantHost;
import com.ikan.positionserver.exceldo.CloudHostDO;
import com.ikan.positionserver.exceldo.PhysicalHostDO;
import com.ikan.positionserver.exceldo.TenantHostDO;
import com.ikan.positionserver.listener.CloudHostListener;
import com.ikan.positionserver.listener.PhysicalHostListener;
import com.ikan.positionserver.listener.TenantHostListener;
import com.ikan.positionserver.response.JsonReturn;
import com.ikan.positionserver.service.ICloudHostService;
import com.ikan.positionserver.service.IDeviceService;
import com.ikan.positionserver.service.IPhysicalHostService;
import com.ikan.positionserver.service.ITenantHostService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;

/**
 * 解析excel文件，得到物理机和云主机的配置信息，并入库
 */
@Slf4j
@RequestMapping("/hostConfig")
@Api(value = "HostConfig", tags = "物理机云主机信息解析")
@Controller
public class HostConfigLoadController {
    @Autowired
    private IPhysicalHostService physicalHostService;
    @Autowired
    private ICloudHostService cloudHostService;

    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private ITenantHostService tenantHostService;

    /**
     * 2024.4.17: 解析excel文件，得到物理机的信息，并保存到数据库中
     *
     * @param request
     * @param response
     * @param file
     * @param model
     * @return
     */
    @ApiOperation(value = "从excel中解析物理主机")
    @RequestMapping(value = "/parsePhysical", method = RequestMethod.POST)
    public JsonReturn parsePhysical(HttpServletRequest request,
                                    HttpServletResponse response,
                                    @RequestParam("file") MultipartFile file,
                                    Model model) {
        FileInputStream fis = null;
        try {
            /*设置编码*/
            request.setCharacterEncoding("UTF-8");

            // 测试MultipartFile接口的各个方法
            log.info("文件类型ContentType:{}", file.getContentType());
            log.info("文件组件名称Name:{}", file.getName());
            log.info("文件原名称OriginalFileName:{}", file.getOriginalFilename());
            log.info("文件大小Size:{}", file.getSize() / 1024 + "KB");

            if (file.isEmpty()) {
                return JsonReturn.buildFailure("文件是空的");
            }

            PhysicalHostListener physicalHostListener = new PhysicalHostListener();
            EasyExcel.read(file.getInputStream(), PhysicalHostDO.class, physicalHostListener).sheet(0).doRead();
            for (PhysicalHostDO physicalHostDO : physicalHostListener.getPhysicalHostDOList()) {
                PhysicalHost physicalHost = new PhysicalHost();
                physicalHost.setAssetId(physicalHostDO.getAssetId());
                physicalHost.setSn(physicalHostDO.getSn());
                physicalHost.setAliasName(physicalHostDO.getAliasName());
                physicalHost.setBizIp(physicalHostDO.getBizIp());
                physicalHost.setOutBandIp(physicalHostDO.getOutBandIp());
                physicalHost.setDeviceType(physicalHostDO.getDeviceType());
                physicalHost.setStatus(physicalHostDO.getStatus());
                physicalHost.setFalutStatus(physicalHostDO.getFaultStatus());
                physicalHost.setFirm(physicalHostDO.getFirm());
                physicalHost.setHeight(Integer.valueOf(physicalHostDO.getHeight()));
                physicalHost.setRackNo(physicalHostDO.getRackNo());
                physicalHost.setRackSeq(physicalHostDO.getRackSeq());
                physicalHost.setCreateTime(new Date());
                physicalHost.setCreator("system");
                physicalHostService.save(physicalHost);
            }
            log.info("保存物理机的信息成功，总记录数:{}", physicalHostListener.getPhysicalHostDOList().size());
            return JsonReturn.buildSuccess("解析成功");
        } catch (Exception e) {
            log.error("修改失败", e);
            return JsonReturn.buildFailure("操作失败" + e.getMessage());
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    /**
     * 2024.4.17: 解析excel文件，得到云主机的信息，并保存到数据库中
     *
     * @param request
     * @param response
     * @param file
     * @param model
     * @return
     */
    @ApiOperation(value = "从excel中解析运营端云主机")
    @RequestMapping(value = "/parseOperationCloud", method = RequestMethod.POST)
    public JsonReturn parseOperationCloud(HttpServletRequest request,
                                 HttpServletResponse response,
                                 @RequestParam("file") MultipartFile file,
                                 Model model) {
        FileInputStream fis = null;
        try {
            /*设置编码*/
            request.setCharacterEncoding("UTF-8");

            // 测试MultipartFile接口的各个方法
            log.info("文件类型ContentType:{}", file.getContentType());
            log.info("文件组件名称Name:{}", file.getName());
            log.info("文件原名称OriginalFileName:{}", file.getOriginalFilename());
            log.info("文件大小Size:{}", file.getSize() / 1024 + "KB");

            if (file.isEmpty()) {
                return JsonReturn.buildFailure("文件是空的");
            }

            CloudHostListener cloudHostListener = new CloudHostListener();
            EasyExcel.read(file.getInputStream(), CloudHostDO.class, cloudHostListener).sheet(0).doRead();
            for (CloudHostDO cloudHostDO : cloudHostListener.getCloudHostDOList()) {
                CloudHost cloudHost = new CloudHost();
                cloudHost.setHostId(cloudHostDO.getHostId());
                cloudHost.setHostName(cloudHostDO.getHostName());
                cloudHost.setMirrorId(cloudHostDO.getMirrorId());
                cloudHost.setMirrorName(cloudHostDO.getMirrorName());
                cloudHost.setStatus(cloudHostDO.getStatus());
                cloudHost.setCloudIp(cloudHostDO.getCloudIp());
                cloudHost.setHostIp(cloudHostDO.getHostIp());
                cloudHost.setRegion(cloudHostDO.getRegion());
                cloudHost.setUpDevice(cloudHostDO.getUpNetworkDevice());
                cloudHost.setOsName(cloudHostDO.getOsName());
                cloudHost.setCreateTime(new Date());
                cloudHost.setCreator("system");
                cloudHostService.save(cloudHost);
            }
            log.info("保存云主机的信息成功，总记录数:{}", cloudHostListener.getCloudHostDOList().size());
            return JsonReturn.buildSuccess("解析成功");
        } catch (Exception e) {
            log.error("修改失败", e);
            return JsonReturn.buildFailure("操作失败" + e.getMessage());
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    /**
     * 2024.4.17: 通过表physical_host的信息来更新device表的信息
     *
     * @return
     */
    @PostMapping
    @ApiOperation(value = "更新物理机的信息")
    public JsonReturn updateDevice() {
        try {
            QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByAsc("id");
            List<Device> deviceList = deviceService.list(queryWrapper);
            int updateCount = 0;
            for (Device device : deviceList) {
                log.info("设备信息, device:{}", device);
                String rackNo = "HLA50404" + device.getRackName();
                int rackSeq = 0;
                if (device.getHeight() == null) {
                    log.info("device的高度信息是空的, device:{}", device);
                    continue;
                }
                if (device.getHeight() == 2) {
                    rackSeq = (device.getUStartId() - 3) / 2;
                }
                int uEndId = device.getUStartId() + device.getHeight();
                QueryWrapper<PhysicalHost> queryPhysicalHostWrapper = new QueryWrapper<>();
                queryPhysicalHostWrapper.eq("rack_no", rackNo);
                queryPhysicalHostWrapper.eq("rack_seq", rackSeq);
                List<PhysicalHost> physicalHostList = physicalHostService.list(queryPhysicalHostWrapper);
                if (CollectionUtils.isEmpty(physicalHostList) == false) {
                    PhysicalHost physicalHost = physicalHostList.get(0);
                    device.setBrand(physicalHost.getFirm());
                    device.setSn(physicalHost.getSn());
                    device.setBizIp(physicalHost.getBizIp());
                    device.setOutBandIp(physicalHost.getOutBandIp());
                    device.setSeq(rackSeq);
                    device.setUpdateTime(new Date());
                    device.setUEndId(uEndId);
                    device.setBizUsage(physicalHost.getAliasName());
                    device.setUpdator("system");
                    deviceService.updateById(device);
                    updateCount++;
                    log.info("更新服务器信息成功, 机架号：{}, 机位号：{}", rackNo, rackSeq);
                } else {
                    log.info("找不到服务器信息, 机架号：{}, 机位号：{}", rackNo, rackSeq);
                }

            }
            log.info("更新服务器信息成功, updateCount：{}", updateCount);

            return JsonReturn.buildSuccess("更新服务器信息成功");
        } catch (Exception e) {
            log.error("修改失败", e);
            return JsonReturn.buildFailure("操作失败" + e.getMessage());
        }

    }


    /**
     * 2024.4.17: 解析excel文件，得到租户端云主机的信息，并保存到数据库中
     *
     * @param request
     * @param response
     * @param file
     * @param model
     * @return
     */
    @ApiOperation(value = "从excel中解析租户端主机")
    @RequestMapping(value = "/parseTenantHost", method = RequestMethod.POST)
    public JsonReturn parseTenetHost(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @RequestParam("file") MultipartFile file,
                                     Model model) {
        FileInputStream fis = null;
        try {
            /*设置编码*/
            request.setCharacterEncoding("UTF-8");

            // 测试MultipartFile接口的各个方法
            log.info("文件类型ContentType:{}", file.getContentType());
            log.info("文件组件名称Name:{}", file.getName());
            log.info("文件原名称OriginalFileName:{}", file.getOriginalFilename());
            log.info("文件大小Size:{}", file.getSize() / 1024 + "KB");

            if (file.isEmpty()) {
                return JsonReturn.buildFailure("文件是空的");
            }

            TenantHostListener tenantHostListener = new TenantHostListener();
            EasyExcel.read(file.getInputStream(), TenantHostDO.class, tenantHostListener).sheet(0).doRead();
            for (TenantHostDO tenantHostDO : tenantHostListener.getTenantHostDOList()) {
                TenantHost tenantHost = new TenantHost();
                tenantHost.setUuid(tenantHostDO.getUuid());
                tenantHost.setHostname(tenantHostDO.getHostname());
                tenantHost.setInstanceId(tenantHostDO.getInstanceId());
                tenantHost.setAppId(tenantHostDO.getAppId());
                tenantHost.setStatus(tenantHostDO.getStatus());

                tenantHost.setHostIp(tenantHostDO.getHostIp());
                tenantHost.setCloudIp(tenantHostDO.getCloudIp());
                tenantHost.setNetwork(tenantHostDO.getNetwork());
                tenantHost.setMirrorName(tenantHostDO.getMirrorName());
                tenantHost.setMirrorId(tenantHostDO.getMirrorId());
                tenantHost.setCreateTime(new Date());
                tenantHost.setCreator("system");
                tenantHostService.save(tenantHost);
            }
            log.info("保存租户端云主机的信息成功，总记录数:{}", tenantHostListener.getTenantHostDOList().size());
            return JsonReturn.buildSuccess("解析成功");
        } catch (Exception e) {
            log.error("修改失败", e);
            return JsonReturn.buildFailure("操作失败" + e.getMessage());
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }


}
